import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { List, InputItem, Button, Icon, Drawer } from 'antd-mobile';
import styled from 'styled-components';
import NavBar from 'components/navBar';
import ChatItem from 'components/chatItem';
import MemberItem from 'components/memberItem';
import ChatInput from './chatInput';
import socket from 'utils/socket';
import * as chatActions from 'actions/chat';
import * as groupActions from 'actions/group';
import { getId } from 'utils/tools';

const wrapperStyle = {
    position: 'absolute',
    left: 0,
    top: 0,
    bottom: '45px',
    width: '100%',
    overflow: 'auto',
    WebkitOverflowScrolling: 'touch'
}

const Wrapper = styled.ul`
    padding: 10px 0;
    background-color: #fff;
   
`
@connect((state, props) => {
    const { id, type } = props.match.params;
    const linkmanId = type === 'group' ? id : getId(state.login.user.id, id);
    const messages = state.chat.linkmans[linkmanId] || [];
    return {
        user: state.login.user,
        messages,
        linkmans: state.chat.linkmans,
        members: state.group.members
    }
}, dispatch => ({
    chatActions: bindActionCreators(chatActions, dispatch),
    groupActions: bindActionCreators(groupActions, dispatch)
}))
export default class Chat extends Component {
    constructor(props) {
        super(props);
        this.state = {
            docked: false,
            open: false
        }
        this.isFetching = false;
    }
    async componentDidMount() {
        if (Object.keys(this.props.linkmans).length === 0) {
            await this.props.chatActions.getLinkmansLastMessage();

        }
        
        // this.props.chatActions.receiveMsg();
        this.scrollNode.scrollTo(0, this.scrollNode.scrollHeight - this.scrollNode.clientHeight)
    }
    
    
    handleScroll = async e => {
        const $div = e.target;
        // 滑动到顶部的时候触发
        const lastHeight = $div.children[0].clientHeight;
        if ($div.scrollTop === 0 && !this.isFetching && $div.scrollHeight > $div.clientHeight) {
            this.isFetching = true;
            const { id, type } = this.props.match.params;
            const _id = getId(this.props.user.id, id, !!(type === 'group'));

            await this.props.chatActions.getLinkmanHistoryMessages(_id, this.props.linkmans[_id] ? this.props.linkmans[_id].length : 0);           
            this.isFetching = false;
        
            // this.scrollNode.scrollTo(0, 100);
        }
    }
    getSnapshotBeforeUpdate() {
        return null;
    }
    componentDidUpdate() {
    }
    handleClick = () => {
        this.setState({
            open: !this.state.open
        })
        this.props.groupActions.getGroupMembers(this.props.match.params.id);
    }
    handleQuit = () => {
        this.props.groupActions.quitGroup(this.props.match.params.id, this.props.user.id).then(res => {
            if (res) {
                this.props.history.push('/home');
            }
        });
    }
    renderSiderbar = list => {
        return (
            <div>
                <Wrapper>
                    {
                        list.map(item => <MemberItem key={item._id} name={item.name} avatar={item.avatar}/>)
                    }
                </Wrapper>
                <Button type='warning' onClick={this.handleQuit}>退出群组</Button>
            </div>
            
        )
    }
    onOpenChange = () => {
        this.setState({
            open: !this.state.open
        })
    }
    render() {
        const { user, messages, location, members } = this.props;
        const { docked, open } = this.state;
        const sidebar = (
            <div>
                <Wrapper>
                    {
                        members.map(item => <MemberItem key={item._id} name={item.name} avatar={item.avatar}/>)
                    }
                </Wrapper>
                <Button type='warning' onClick={this.handleQuit}>退出群组</Button>
            </div>
        )
        return (
            <div>
                <NavBar
                    icon={<Icon type="left" />}
                    rightContent={<span onClick={this.handleClick.bind(this)}>查看</span>}
                    onLeftClick={() => { this.props.history.push('/home'); }}
                >
                    {location.state.name}
                </NavBar>
                <Drawer position='right'
                    open={open}
                    sidebar={sidebar}
                    onOpenChange={this.onOpenChange}
                    style={{top: 45}}
                    overlayStyle={{opacity: 0}}
                    sidebarStyle={{height: '100%', width: 300, backgroundColor: '#fff'}}
                >
                    <div style={wrapperStyle} onScroll={this.handleScroll} ref={node => { this.scrollNode = node; }}>
                        <Wrapper>
                            {
                                messages.map(message => {
                                    const from = { ...message.from };
                                    const self = user.id === from._id;
                                    return (
                                        <ChatItem key={message._id} 
                                            content={message.content} 
                                            self={self}
                                            username={self ? user.name : from.name}
                                        />
                                    )
                                })
                            }
                        </Wrapper>  
                    </div>
                    <ChatInput />           
                    
                </Drawer>
                
            </div>
        )
    }
}